/*
 * Copyright (c) 2009 by Chances.
 * $HeadURL$:
 * $Author: chenxx $:
 * $Date: 2010/06/08 08:23:01 $:
 * $Rev$:
 */
package chances.iptv.web;

import java.io.IOException;
import java.util.Locale;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * Class comments.
 * 
 * @author <a href="mailto:chenxx@chances.com.cn">chenxx</a>
 */
public class EPGSSOInterceptor extends HandlerInterceptorAdapter {

    public static final String SSO_TOKEN = "SSO_TOKEN";

    private String failPage;

    private String ssoURL;

    private String spId;

    /*
     * (non-Javadoc)
     * 
     * @see
     * org.springframework.web.servlet.HandlerInterceptor#afterCompletion(javax
     * .servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
     * java.lang.Object, java.lang.Exception)
     */
    public void afterCompletion(HttpServletRequest arg0,
            HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {

    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * org.springframework.web.servlet.HandlerInterceptor#postHandle(javax.servlet
     * .http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
     * java.lang.Object, org.springframework.web.servlet.ModelAndView)
     */
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
            Object arg2, ModelAndView arg3) throws Exception {

    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * org.springframework.web.servlet.HandlerInterceptor#preHandle(javax.servlet
     * .http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
     * java.lang.Object)
     */
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object arg2) throws Exception {
        response.setLocale(new Locale(new String("en")));
        String currentURL = request.getRequestURL().toString();
        String queryString = request.getQueryString();
        if (StringUtils.isNotEmpty(queryString)) {
            currentURL = currentURL + "?" + queryString;
        }
        request.setAttribute("currentURL", currentURL);
        if (isTestUser(request)) {
            return true;
        }
        if (UserSession.existUserSession(request)) {
            return true;
        } else {
            return doSignon(request, response);

        }

    }

    private boolean doSignon(HttpServletRequest request,
            HttpServletResponse response) throws Exception, ServletException,
            IOException {
        String result = request.getParameter("result");
        String userID = request.getParameter("userID");

        if (result == null) {
            result = request.getParameter("Result");
        }
        if (StringUtils.isEmpty(result) && StringUtils.isEmpty(userID)) {
            return ssoAuth(request, response);
        } else {
            if ("0".equals(result) || StringUtils.isNotEmpty(userID)) {
                UserSession.createUserSession(request, true);
                return true;
            } else {
                RequestDispatcher aRequestDispatcher = request
                        .getRequestDispatcher(this.failPage);
                if (aRequestDispatcher != null) {
                    aRequestDispatcher.forward(request, response);
                    return false;
                }
            }
        }
        return true;
    }

    private boolean ssoAuth(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        String returnURL = null;
        String path = request.getServletPath();
        String ssoReturnURL = "http://" + request.getLocalAddr() + ":"
                + request.getLocalPort() + request.getContextPath();
        if (StringUtils.isNotEmpty(ssoReturnURL)) {
            String queryString = request.getQueryString();
            if (queryString != null) {
                queryString = "?" + queryString;
            } else {
                queryString = "";
            }
            returnURL = ssoReturnURL + path + queryString;
        } else {
            returnURL = request.getRequestURL().toString();
        }
        returnURL = java.net.URLEncoder.encode(returnURL, "UTF-8");
        String toSsoURL = this.ssoURL + "?SPID=" + spId
                + "&Action=UserTokenRequest&ReturnInfo=" + returnURL
                + "&ReturnURL=" + returnURL;
        response.sendRedirect(toSsoURL);
        return false;
    }

    private boolean isTestUser(HttpServletRequest request) {
        String id = request.getParameter("testId");
        if (StringUtils.isNotEmpty(id)
                && (id.startsWith("chances") || id.matches("\\d*"))) {
            UserSession userSession = UserSession.createUserSession(request,
                    true);
            userSession.setUserId(id);
            UserSession.saveSession(request, userSession);
            return true;
        } else {
            return false;
        }

    }

    /**
     * @param failPage
     *            the failPage to set
     */
    public void setFailPage(String failPage) {
        this.failPage = failPage;
    }

    /**
     * @param ssoURL
     *            the ssoURL to set
     */
    public void setSsoURL(String ssoURL) {
        this.ssoURL = ssoURL;
    }

    /**
     * @param spId
     *            the spId to set
     */
    public void setSpId(String spId) {
        this.spId = spId;
    }

}
